package com.haidao.admin.component.service.thirdpart.impl;

import cn.com.jit.ida.util.pki.encoders.Base64;
import cn.com.jit.new_vstk.AdvanceSignClient;
import cn.com.jit.new_vstk.Bean.CertIdParams;
import cn.com.jit.new_vstk.Bean.CertParams;
import cn.com.jit.new_vstk.Bean.SignResult;
import cn.com.jit.new_vstk.Bean.VerifyResult;
import cn.com.jit.new_vstk.exception.NewCSSException;
import com.haidao.admin.component.configuration.properties.CssConfigProperties;
import com.haidao.admin.component.service.thirdpart.SignatureService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ThirdAreaSignatureServiceImpl implements SignatureService {
    @Resource
    private CssConfigProperties cssConfigProperties;

    // 3.1.9
    @Override
    public String signature(String str) {
        String certId = "cmac";//证书标识
        try {
            //如果找不到类路径下的cssconfig.properties文件，请写绝对路径
            AdvanceSignClient client = new AdvanceSignClient(cssConfigProperties.getConfig());

            //p1签名
            SignResult result = client.p1Sign(certId, str.getBytes());

            byte[] signData = result.getSignData();//获取未做base64的签名结果
            String base64Str = new String(Base64.encode(signData));
            log.info("签名结果为：" + base64Str);
            return base64Str;
        } catch (NewCSSException e) {
            log.info("****签名失败****");
            log.info("错误号为：" + e.getCode());
            log.info("错误描述为: " + e.getDescription());
            log.info("日志标识码: " + e.getSerialNumber());
        }
        return null;
    }

    // 3.1.10
    @Override
    public boolean verify(String str, String signature) {
        AdvanceSignClient client;
        try {
            // 如果找不到类路径下的cssconfig.properties文件，请写绝对路径
            client = new AdvanceSignClient("cssconfig.properties");

            String certId = "cmac";
            CertParams certParam = new CertIdParams(certId);

            //需要验签名的原文
            byte[] srccode = str.getBytes();

            //获取非base64格式的签名结果
            byte[] signData = Base64.decode(signature);

            VerifyResult result = client.p1Verify(signData, srccode, certParam);

            System.out.println("****验签成功****");
            System.out.println("    证书subjectdn: " + result.getSubjectdn());
            System.out.println("    证书issuer： " + result.getIssure());
            System.out.println("    证书SN： " + result.getSn());
            System.out.println("    证书实体base64： " + result.getDsCert());
            return true;
        } catch (NewCSSException e) {
            log.info("****验签失败****");
            log.info("错误号为：" + e.getCode());
            log.info("错误描述为: " + e.getDescription());
            log.info("日志标识码: " + e.getSerialNumber());
        }

        return false;
    }


}
